﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Scheduling.Models;

namespace MultipleBooking
{
    class GraphDrawer
    {
        public static Bitmap DrawGraph(List<Booking> bookingList, List<Room> roomList)
        {
            bookingList = bookingList.OrderBy(b => b.StartDate).ToList();
            DateTime firstDate = bookingList.First().StartDate;
            DateTime lastDate = bookingList.Last().StartDate;
            int roomCount = roomList.Count;
            int roomHeight = 8;
            var bookedColor = Color.IndianRed;
            var freeColor = Color.LightGreen;
            var invalidColor = Color.Yellow;
            int firstPixelShift = firstDate.DayOfYear;
            Bitmap bmp = new Bitmap((lastDate.DayOfYear - firstDate.DayOfYear) * 4 + 8, roomHeight * roomCount);

            while( firstDate != lastDate )
            {
                if (firstDate.Hour == 12) 
                    firstDate = firstDate.AddHours(1);

                bool invalidDay = false;
                if (firstDate.DayOfWeek == DayOfWeek.Saturday || firstDate.DayOfWeek == DayOfWeek.Sunday)
                {
                    for (int y = 0; y < roomHeight * roomCount; y++)
                        bmp.SetPixel((firstDate.DayOfYear - firstPixelShift) * 4 + (firstDate.Hour - 8) / 2, y, invalidColor);
                    invalidDay = true;
                }

                for (int r = 0; r < roomList.Count; r++ )
                {
                    bool hasBooking = false;
                    foreach (var b in bookingList)
                    {
                        if (b.StartDate == firstDate && b.Room == roomList[r])
                            hasBooking = true;
                    }
                    if (hasBooking)
                        for (int y = 0; y < roomHeight; y++)
                            bmp.SetPixel((firstDate.DayOfYear - firstPixelShift) * 4 + (firstDate.Hour - 8) / 2, y + r * roomHeight, bookedColor);
                    else if (!invalidDay)
                        for (int y = 0; y < roomHeight; y++)
                            bmp.SetPixel((firstDate.DayOfYear - firstPixelShift) * 4 + (firstDate.Hour - 8) / 2, y + r * roomHeight, freeColor);
                }

                if (firstDate.Hour == 17)
                {
                    firstDate = firstDate.AddHours(-9);
                    firstDate = firstDate.AddDays(1);
                }
                else
                    firstDate = firstDate.AddHours(2);
            }

            return bmp;
        }
    }
}
